<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat UI</title>
    <style>
    a {
      color: green;
    }
    body {
        background-color: #333;
        color: #eee;
        margin: 0;
    }
      #chat-window {
            border: 1px solid black;
            height: calc(90vh - 100px);
            overflow-y: scroll;
            padding: 5px;
        }
      .message {
        margin: 10px;
        padding: 10px;
        border-radius: 5px;
        display: flex;
        align-items: center;
        max-width: 80%;
      }
      .user-icon {
        background-color: #102133;
        color: #fff;
        font-size: 20px;
        width: 30px;
        height: 30px;
        border-radius: 20%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 10px;
      }
      .robot-icon {
        background-color: #103218;
        color: #fff;
        font-size: 20px;
        width: 90px;
        height: 30px;
        border-radius: 30%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 10px;
        margin-top: 10px;
        margin-bottom: 10px;
      }
      .user-message {
        background-color: #333;
        color: #ccc;
        /* text-align: right; */
        margin-top: 10px;
        /* margin-right: 10px; */
        margin-bottom: 10px;
        font-size: 30px;
        white-space: pre-wrap;
        padding: 10px;
      }
      .robot-message {
        font-size: 30px;
        background-color: rgb(87, 85, 85);
        margin-top: 10px;
        margin-bottom: 10px;
        white-space: pre-wrap;
        color: #ccc;
        padding: 10px;
      }
      .error-message {
        font-size: 30px;
        font-style: italic;
        background-color: rgb(87, 85, 85);
        margin-top: 10px;
        margin-bottom: 10px;
        margin-left: 10px;
        color: rgb(233, 250, 76);
      }
        textarea#message-input {
        width: calc(75%);
        padding: 10px;
        border-radius: 5px;
        border: 1px solid #ccc;
        margin-top: 10px;
        resize: vertical;
        font-size: 26px;
        min-height: 50px; /* adjust this value to set the minimum height of the textarea */
        display: inline-block; /* Display the input box and submit button inline */
        vertical-align: bottom; /* Align them to the bottom */
      }
      button#submit {
        width: calc(15%);
        padding: 10px;
        min-height: 72px; /* adjust this value to set the minimum height of the textarea */
        border-radius: 5px;
        border: 1px solid #ccc;
        margin-left: 10px;
        background-color: #007bff;
        color: #fff;
        font-size: 16px;
        display: inline-block; /* Display the input box and submit button inline */
        vertical-align: bottom; /* Align them to the bottom */
      }
    </style>
  </head>
  <body>
    <div id="chat-window">
    </div>
    <textarea id="message-input" placeholder="在这里输入消息..."></textarea><button id="submit">发送</button>
    <script>
      const chatWindow = document.getElementById('chat-window');
      const messageInput = document.getElementById('message-input');

      let messages = [];
      const messageElement = document.createElement('div');
        messageElement.classList.add('robot-message');
        const iconElement = document.createElement('div');
        iconElement.classList.add('robot-icon');
        iconElement.textContent = '百事通';
        const contentElement = document.createElement('div');
        contentElement.classList.add('robot-message');
        contentElement.innerHTML = "(3.5 stable version)我叫许三多，可以通过对话来实现很多任务。" +
        "您可以这样问我：<br>"+
        "   \"陪我聊会天儿吧\"<br>" +
        "   \"甲流和新冠是同一种病毒吗？\"<br>" +
        "   \"写一个推广青岛啤酒的方案\"<br>" +
        "   \"朋友结婚了，该怎么写祝福语\"<br>" +
        "   \"孕妇感到恶心，丈夫能做些什么？\"<br>" +
        "   \"孤独感，是个体的特质还是人类的共性\"<br>" +
        "   \"请以初中三年级能理解的方式解释量子计算\"<br>" +
        "   \"请写一段符合国人审美的城市爱情故事，适合做成视频文案\"<br>" +
        "我还能学习和不断改进，以更好地为您服务。但，我所提供的信息可能有事实性的错误，请一定要有自己的判断！<br><br>强烈建议查看<a href='https://gitee.com/xu-zhanwei/chatanywhere'>说明</a>了解更多！<br><br><a href='https://gitee.com/xu-zhanwei/chatanywhere/blob/master/Support.md'>点击此处支持项目后续开发</a>";
        messageElement.appendChild(iconElement);
        messageElement.appendChild(contentElement);
        chatWindow.appendChild(messageElement);
      document.getElementById("submit").addEventListener("click", function() {
        sendMessage();
      });
      function disableInput() {
        messageInput.disabled = true;
        document.getElementById("submit").disabled = true;
      }

      function enableInput() {
        messageInput.disabled = false;
        document.getElementById("submit").disabled = false;
      }

      let timerId = null;

      function setTimer() {
        timerId = setTimeout(() => {
        const errorMessage = '糟糕！我的回答好像中断了！你可以重新问一遍吗？如果还是不行，那么请刷新此页面并检查下网络连接是否顺畅。';
        messages.push({"role": "system", "content": errorMessage});
        const errorMessageElement = document.createElement('div');
        errorMessageElement.classList.add('error-message');
        errorMessageElement.textContent = errorMessage;
        chatWindow.appendChild(errorMessageElement);
        chatWindow.scrollTop = chatWindow.scrollHeight;
        enableInput();
        }, 30000);
        }
      function resetTimer() {
        clearTimeout(timerId);
        setTimer();
      }
      function sendMessage() {
        disableInput();
        const message = messageInput.value;
        if (message.trim() === '') {
        enableInput();
        return;
        }
        messageInput.value = '';
        messages.push({"role": "user", "content": message});
        if (messages.length > 4) {
        messages.shift();
        }
        const messageElement = document.createElement('div');
        messageElement.classList.add('user-message');
        const iconElement = document.createElement('div');
        iconElement.classList.add('user-icon');
        iconElement.textContent = '你';
        const contentElement = document.createElement('div');
        contentElement.classList.add('user-message');
        contentElement.innerHTML = message.replace(/(\r\n|\n|\r)/gm, "<br>");;
        messageElement.appendChild(iconElement);
        messageElement.appendChild(contentElement);
        chatWindow.appendChild(messageElement);
        chatWindow.scrollTop = chatWindow.scrollHeight;
        setTimer();
        // Send a POST request to the server
        fetch('/message', {
        method: 'POST',
        headers: {
        'Content-Type': 'application/json'
        },
        body: JSON.stringify({"message": messages}),
        timeout: 10000,
        })
        .then(response => {

            // Display the robot icon
            const iconElement = document.createElement('div');
            iconElement.classList.add('robot-icon');
            iconElement.textContent = '百事通';
            const messageElement = document.createElement('div');
            messageElement.classList.add('robot-message');
            messageElement.appendChild(iconElement);
            chatWindow.appendChild(messageElement);

            // Create a single element to display the received text
            const contentElement = document.createElement('div');
            contentElement.classList.add('robot-message');
            messageElement.appendChild(contentElement);
            chatWindow.scrollTop = chatWindow.scrollHeight;

            // Start reading the response stream
            const reader = response.body.getReader();
            let buffer = '';
            reader.read().then(function processText({ done, value }) {
            if (done) {
            // The stream is finished, display the received text
            messages.push({"role": "assistant", "content": buffer});
            if (messages.length > 4) {
            messages.shift();
            }
            chatWindow.scrollTop = chatWindow.scrollHeight;
            enableInput();
            clearTimeout(timerId);
            return;
            }

        // Add the received chunk to the buffer and display the current content
        text = new TextDecoder("utf-8").decode(value);
        buffer += text;
        contentElement.innerHTML = buffer.replace(/(\r\n|\n|\r)/gm, "<br>");
        chatWindow.scrollTop = chatWindow.scrollHeight;
        resetTimer();

        // Process the next chunk of text
        reader.read().then(processText);
        });

        })
        .catch(error => {
        const errorMessage = document.createElement('div');
        errorMessage.classList.add('error-message');
        errorMessage.textContent = '连接已断开，请检查网络连接后重新尝试。';
        clearTimeout(timerId);
        chatWindow.appendChild(errorMessage);
        chatWindow.scrollTop = chatWindow.scrollHeight;
        enableInput();
        });
      }
    </script>
  </body>
</html>
